package com.PDP.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.security.Key;
import java.util.Date;
import java.util.Map;
import java.util.function.Function;

@Service
public class JWTService {
    private static final int TOKEN_EXP_TIME=1000*1000*60*24;
    private static final String SECRET_KEY="f035512b6210542f261ceac685466dc2773d5c4ceef71ee9e424021fd636dbe9";
    public boolean isTokenValid(String token,UserDetails userDetails){
        final String username=extractLogin(token);
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);

    }

    private boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    private Date extractExpiration(String token) {
        return extractClaim(token,Claims::getExpiration);
    }

    public String generateToken(Map<String,Object> extraClaims, UserDetails userDetails){
        return Jwts.builder().setClaims(extraClaims).setSubject(userDetails.getUsername())
                .setIssuedAt(new Date(System.currentTimeMillis())).setExpiration(new Date(System.currentTimeMillis()+TOKEN_EXP_TIME))
                .signWith(getSigningKey(), SignatureAlgorithm.HS256).compact();

    }
    public String extractLogin(String jwt){
        return extractClaim(jwt,Claims::getSubject);
    }
    private Claims extractAllClaims(String token){
        return Jwts.parserBuilder().setSigningKey(getSigningKey()).build()
                .parseClaimsJws(token).getBody();
    }

    public <T> T extractClaim(String token, Function<Claims,T> claimsResolver){
        final Claims claims=extractAllClaims(token);
        return claimsResolver.apply(claims);
    }
    private Key getSigningKey() {
        byte[] keyB= Decoders.BASE64.decode(SECRET_KEY);
        return Keys.hmacShaKeyFor(keyB);
    }


}
